import ssl
from datetime import datetime, timedelta
from OpenSSL import crypto
import os
import sys
import site
# 获取当前虚拟环境的lib目录路径
venv_lib_dir = next(p for p in sys.path if p.startswith(site.getsitepackages()[0]) and 'lib' in p)

# 获取虚拟环境的地址
venv_address = venv_lib_dir.replace('lib', '')

print(f"当前虚拟环境的地址是: {venv_address}")
# root_path = Path(__file__).resolve().parent.parent
if os.name == 'nt':
    root_path = os.path.dirname(os.path.realpath(sys.argv[0]))+'\\template\\'
else:
    root_path = '/var/project/inv_tool/template/'
print(root_path)

def create_self_signed_cert(cert_dir, is_ca=False, days=365):
    # 创建一个RSA密钥
    private_key = crypto.PKey()
    private_key.generate_key(crypto.TYPE_RSA, 2048)

    # 创建一个自签名证书
    cert = crypto.X509()
    cert.get_subject().CN = "My Self Signed Cert"
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(days * 24 * 60 * 60)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(private_key)
    cert.sign(private_key, 'sha256')

    # 保存证书和密钥
    with open(f"{cert_dir}/cert.pem", "wb") as cert_file:
        cert_file.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    with open(f"{cert_dir}/key.pem", "wb") as key_file:
        key_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, private_key))

    if is_ca:
        # 如果是CA证书，还需要CA根证书和私钥
        pass


# 使用函数生成证书，证书保存在当前目录下的cert_and_key文件夹中
create_self_signed_cert(root_path)